package cn.com.gridinfo.sooc.core.my.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.StringUtils;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import org.apache.http.message.BasicNameValuePair;

import java.util.HashMap;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocFragment;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.login.activity.LoginActivity;
import cn.com.gridinfo.sooc.core.my.commen.CodeConst;
import cn.com.gridinfo.sooc.core.my.course.MyCollectActivity;
import cn.com.gridinfo.sooc.core.my.course.MyCourseActivity;
import cn.com.gridinfo.sooc.core.my.dao.MyDao;
import cn.com.gridinfo.sooc.core.my.msg.activity.MsgActivity;
import cn.com.gridinfo.sooc.core.my.msg.dao.NoticeDao;
import cn.com.gridinfo.sooc.core.my.note.activity.MyNoteActivity;
import cn.com.gridinfo.sooc.core.my.order.MyOrderActivity;
import cn.com.gridinfo.sooc.core.my.personal.activity.PersonalActivity;
import cn.com.gridinfo.sooc.core.my.setting.activity.SettingActivity;
import cn.com.gridinfo.sooc.utils.BlurUtil;
import cn.com.gridinfo.sooc.utils.IntentUtil;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * <我的>主界面
 * Created by 刘晓晨 on 2015/12/7.
 */
public class MyMainFragment extends BaseSoocFragment {
    @InjectView(R.id.rl_user_info)//用户信息大背景
            RelativeLayout rl_user_info;
    @InjectView(R.id.user_icon)// 登录后的头像
            CircleImageView headimgLogin;
    @InjectView(R.id.username_login)//登录后的昵称
            TextView usernameLogin;
    @InjectView(R.id.clickLogin)//点击登录
            TextView btnClickLogin;
    @InjectView(R.id.message) // 我的消息（小红点）
            TextView message;
    @InjectView(R.id.studingCourseCount)
    TextView studingCourseCount;//我在学课程数量
    @InjectView(R.id.studiedCourseCount)
    TextView studiedCourseCount;//已学完课程数量
    @InjectView(R.id.order_tv)
    TextView orderTv;//订单按钮

    private MyDao dao; //dao
    private String identitytype;
    View view;

    public static MyMainFragment newInstance() {
        return new MyMainFragment();
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isVisible()) {
            loadView();
        }
    }

    private void loadView() {
        if (!Arad.preferences.getBoolean(LocalMark.IS_AUTO_LOGIN.getName(), false)) {
            //未登录
            btnClickLogin.setVisibility(View.VISIBLE);
            usernameLogin.setVisibility(View.GONE);
            headimgLogin.setImageResource(R.mipmap.my_user_icon_defaut);
            rl_user_info.setBackgroundResource(R.mipmap.my_unlogin_bc);
        } else {
            //已登录
            btnClickLogin.setVisibility(View.GONE);
            usernameLogin.setVisibility(View.VISIBLE);
            dao.myMainView();//获取我的基本信息
            getMyMsg();//获取我的消息数据（课程通知和讨论通知）
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.my_main_layout, null);
        ButterKnife.inject(this, view);
        dao = new MyDao(this);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    getResources().getDimensionPixelSize(R.dimen.height_285));
            rl_user_info.setLayoutParams(params);
            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.my_user_icon_size),
                    getResources().getDimensionPixelSize(R.dimen.my_user_icon_size));
            params1.topMargin = getResources().getDimensionPixelSize(R.dimen.space_60);
            params1.addRule(RelativeLayout.CENTER_HORIZONTAL);
            headimgLogin.setLayoutParams(params1);
        } else {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    getResources().getDimensionPixelSize(R.dimen.height_260));
            rl_user_info.setLayoutParams(params);
            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.my_user_icon_size),
                    getResources().getDimensionPixelSize(R.dimen.my_user_icon_size));
            params1.addRule(RelativeLayout.CENTER_HORIZONTAL);
            params1.topMargin = getResources().getDimensionPixelSize(R.dimen.space_36);
            headimgLogin.setLayoutParams(params1);
        }
        //如果平台不收费，则不显示订单
        if (!Arad.preferences.getBoolean(LocalMark.IS_PAY.getName())) {
            orderTv.setVisibility(View.GONE);
        }
        return view;
    }


    //判断是否显示小红点
    private void getMyMsg() {
        dao.myMsgMain();
    }

    //初始化界面数据
    private void initView() {
        studiedCourseCount.setText(dao.getStudiedCourseCount());
        studingCourseCount.setText(dao.getStudingCourseCount());
        usernameLogin.setText(Arad.preferences.getString(LocalMark.USER_NICKNAME.getName(), ""));//拿到昵称(显示）
        identitytype = Arad.preferences.getString(LocalMark.USER_IDENTITYTYPE.getName(), "5");//拿到用户类型
        String imageUrl = Arad.preferences.getString(LocalMark.USER_HEADIMG.getName(), ""); //拿到头像（显示）
        if (!StringUtils.isNull(imageUrl) && imageUrl.contains("http")) {
            Picasso.with(getActivity()).load(imageUrl).resize(getResources().getDimensionPixelSize(R.dimen.my_user_icon_size),
                    getResources().getDimensionPixelSize(R.dimen.my_user_icon_size)).
                    centerCrop().into(new Target() {
                @Override
                public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {//加载成功
                    setBackground(bitmap);
                    headimgLogin.setImageBitmap(bitmap);
                }

                @Override
                public void onBitmapFailed(Drawable errorDrawable) {
                    headimgLogin.setImageResource(R.mipmap.my_user_icon_defaut);//加载失败
                    Log.i("用户头像", "onBitmapFailed(Drawable errorDrawable)");
                }

                @Override
                public void onPrepareLoad(Drawable placeHolderDrawable) {//正在加载
                    headimgLogin.setImageResource(R.mipmap.my_user_icon_defaut);
                    Log.i("用户头像", "onPrepareLoad(Drawable errorDrawable)");
                }
            });
        } else {
            headimgLogin.setImageResource(R.mipmap.my_user_icon_defaut);
            rl_user_info.setBackgroundResource(R.mipmap.my_unlogin_bc);
            Log.i("用户头像", "异常" + imageUrl);
        }
    }

    /*
     * 设置毛玻璃背景
     *
     * @param id 背景图片id
     */
    private void setBackground(Bitmap bitMapImg) {
        final Bitmap blurBmp = BlurUtil.fastblur(getContext(), bitMapImg, 20);//0-25，表示模糊值
        final Drawable newBitmapDrawable = new BitmapDrawable(blurBmp); // 将Bitmap转换为Drawable
        rl_user_info.post(new Runnable()  //调用UI线程
        {
            @Override
            public void run() {
                rl_user_info.setBackgroundDrawable(newBitmapDrawable);//设置背景
            }
        });
    }

    //请求成功返回数据
    @Override
    public void onRequestSuccess(int requestCode) {
        super.onRequestSuccess(requestCode);
        switch (requestCode) {
            case CodeConst.GET_MYINFO:
                if (dao.status.equals("0")) {
                    initView();//初始化个人信息
                }
                break;
            case CodeConst.MSGMAIN:
                //我的消息数据
                if (dao.status.equals("0")) {
                    initViewAndSaveTime();
                }
                break;

        }
    }

    //我的消息需要传递的数据
    private Bundle mBundle;

    //初始化消息红点标示
    private void initViewAndSaveTime() {
        //默认为false，表示无此类型的消息
        //推送消息false, 课程通知消息 fale, 讨论通知消息 false, 系统消息 false,
        boolean newTs = false, newKc = false, newTl = false, newSys = false;
        mBundle = new Bundle();
        HashMap<String, Object> noticeInfo = new HashMap<>();
        String suid = Arad.preferences.getString(LocalMark.SERVER_ID.getName().toString()) + "_"
                + Arad.preferences.getString(LocalMark.USER_UID.getName().toString());
        noticeInfo = new NoticeDao().queryLatestNotice("suid='" + suid + "'");
        if (null != noticeInfo && !noticeInfo.isEmpty() && noticeInfo.get("status").equals("0")) {
            //有新的推送通知
            newTs = true;
        }

        //获取消息信息
        if (null != dao.getMessage() && !dao.getMessage().isEmpty()) {

            //获取课程通知消息内容
            if (dao.getMessage().containsKey("notice") && null != dao.getMessage().get("notice") && !dao.getMessage().get("notice").isEmpty()) {
                Map<String, String> noticeMap = dao.getMessage().get("notice");
                //判断课程通知消息,1 本地是否有课程通知消息时间 并且获取的时间是否大于等于当前时间
                long msg_kc_newtime = Long.parseLong(noticeMap.get("input_time"));//新获取的课程通知时间
                long msg_kc_localtime = Arad.preferences.getLong(LocalMark.MSG_KCINPUT_TIME.getName(), 0l);//本地存储的课程通知时间,默认为0;
                //新获取的时间-本地存储的时间>0 说明有新的课程通知消息
                if (msg_kc_newtime - msg_kc_localtime > 0) {
                    //有新的课程通知
                    newKc = true;
                }

                mBundle.putString("kctz", noticeMap.get("title"));//课程通知标题内容
                mBundle.putString("kcTime", noticeMap.get("sj"));//课程通知格式化显示时间
                mBundle.putLong("kcInput_time", Long.parseLong(noticeMap.get("input_time")));//是否有新通知时间标识
            }

            //获取讨论通知消息内容
            if (dao.getMessage().containsKey("discuss") && null != dao.getMessage().get("discuss") && !dao.getMessage().get("discuss").isEmpty()) {
                Map<String, String> discussMap = dao.getMessage().get("discuss");

                //判断讨论通知消息,1 本地是否有讨论通知消息时间 并且获取的时间是否大于等于当前时间
                long msg_tl_newtime = Long.parseLong(discussMap.get("input_time"));//新获取的课程通知时间
                long msg_tl_localtime = Arad.preferences.getLong(LocalMark.MSG_TLINPUT_TIME.getName(), 0l);//本地存储的课程通知时间,默认为0;
                //新获取的时间-本地存储的时间>0 说明有新的讨论通知消息
                if (msg_tl_newtime - msg_tl_localtime > 0) {
                    //有新的讨论通知
                    newTl = true;
                }


                mBundle.putString("tltz", discussMap.get("title"));//讨论标题
                mBundle.putString("tlTime", discussMap.get("sj"));//讨论显示的格式化时间
                mBundle.putLong("tlInput_time", Long.parseLong(discussMap.get("input_time")));//讨论是否更新时间标识
            }

            //系统通知，V3.0.0版本不上
//            if (dao.getMessage().containsKey("system") && null != dao.getMessage().get("system") && !dao.getMessage().get("system").isEmpty()) {
//                Map<String, String> systemMap = dao.getMessage().get("system");
//                if (StringUtils.isNull(Arad.preferences.getString("sysInput_time")) ||
//                        (!systemMap.get("input_time").equals(Arad.preferences.getString("sysInput_time"))
//                                && Long.parseLong(systemMap.get("input_time")) -
//                                Long.parseLong(Arad.preferences.getString("sysInput_time")) > 0)) {
//                    //有新的系统通知
//                    newSys = true;
//                }
//                mBundle.putString("xttz", systemMap.get("title"));
//                mBundle.putString("xtTime", systemMap.get("sj"));
//                if (systemMap.containsKey("input_time")) {
//                    mBundle.putString("sysInput_time", systemMap.get("input_time"));
//                } else {
//                    mBundle.putString("sysInput_time", System.currentTimeMillis() + "");
//                }
//            }
        }
        if (newTs || newKc || newTl || newSys) {
            //显示红点
            message.setVisibility(View.VISIBLE);
        } else {
            message.setVisibility(View.GONE);
        }
    }


    //请求失败
    @Override
    public void onRequestFaild(int requestCode, String errorNo, String errorMessage) {
        super.onRequestFaild(requestCode, errorNo, errorMessage);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    // 未登录时 点击“点击登录”
    @OnClick(R.id.clickLogin)
    void clickLogin() {
        startActivityForResult(new Intent(getContext(), LoginActivity.class), 00);
        AnimUtil.intentPushUp(getActivity());
    }

    //点击编辑 修改个人信息
    @OnClick(R.id.username_login)
    void myInfo() {
        //进入个人信息修改昵称和头像后更新显示
        startActivityForResult(new Intent(getContext(), PersonalActivity.class), 11);
        AnimUtil.intentSlidIn(getActivity());
    }

    //头像点击
    @OnClick(R.id.user_icon)
    void onHeadImgClick() {
        myInfo();
    }

    //点击设置
    @OnClick(R.id.rl_btn_setting)
    void setting() {
        if (!Arad.preferences.getBoolean(LocalMark.IS_AUTO_LOGIN.getName(), false)) {
            startActivityForResult(new Intent(getContext(), LoginActivity.class), 00);
            AnimUtil.intentPushUp(getActivity());
        } else {
            Intent intent = new Intent(getActivity(), SettingActivity.class);
            if (!StringUtils.isNull(identitytype)) {
                //用户类型2：老师 3：学生 5：游客
                intent.putExtra("identitytype", identitytype);
            } else {
                //为空 就是游客
                intent.putExtra("identitytype", "5");
            }
            intent.putExtra("imgUrl", Arad.preferences.getString(LocalMark.USER_HEADIMG.getName()));//用户头像
            intent.putExtra("xm", Arad.preferences.getString(LocalMark.USER_REALNAME.getName()));//用户姓名
            intent.putExtra("name", usernameLogin.getText().toString().trim());
            intent.putExtra("sfzjh", Arad.preferences.getString(LocalMark.USER_SFZJH.getName()));//用户身份证号
            intent.putExtra("BoundedPhoneNumber", Arad.preferences.getString(LocalMark.USER_TEL.getName()));//手机号
            startActivityForResult(intent, 22);//请求码 ：22 点击设置中的退出登录
            AnimUtil.intentSlidIn(getActivity());
        }
    }

    //点击我的消息
    @OnClick(R.id.rl_btn_message)
    void myMsg() {
        if (!Arad.preferences.getBoolean(LocalMark.IS_AUTO_LOGIN.getName(), false)) {
            startActivityForResult(new Intent(getContext(), LoginActivity.class), 00);
            AnimUtil.intentPushUp(getActivity());
        } else {
            Intent intent = new Intent(getActivity(), MsgActivity.class);
            if (mBundle != null)
                intent.putExtras(mBundle);
            startActivityForResult(intent, 33);//请求值，当都查看了信息才返回隐藏红点
            AnimUtil.intentSlidIn(getActivity());
        }
    }

    //点击我的笔记
    @OnClick(R.id.note_tv)
    void myNote() {
//        if (!Arad.preferences.getBoolean(LocalMark.IS_AUTO_LOGIN.getName(), false)) {
//            startActivityForResult(new Intent(getContext(), LoginActivity.class), 00);
//            AnimUtil.intentPushUp(getActivity());
//        } else {
        IntentUtil.intentSlidIn(getActivity(), MyNoteActivity.class, 00);
//        }
    }

    //点击  我在学课程
    @OnClick(R.id.studingCourse_rl)
    void onStudingCourseClick() {
        IntentUtil.intentSlidIn(getActivity(), MyCourseActivity.class, 00, new BasicNameValuePair("from", "studing"));
    }

    //点击  已学完课程
    @OnClick(R.id.studiedCourse_rl)
    void onStudiedCourseClick() {
        IntentUtil.intentSlidIn(getActivity(), MyCourseActivity.class, 00, new BasicNameValuePair("from", "studied"));
    }

    //点击 收藏
    @OnClick(R.id.collect_tv)
    void onCollectClick() {
        IntentUtil.intentSlidIn(getActivity(), MyCollectActivity.class, 00);
    }


    //点击 订单
    @OnClick(R.id.order_tv)
    void onOrderClick() {
        IntentUtil.intentSlidIn(getActivity(), MyOrderActivity.class, 00,new BasicNameValuePair("from","my"));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 00:
                loadView();
                break;
            case 11://加载新头像 11 或者新昵称
                if (resultCode == Activity.RESULT_OK) {
                    usernameLogin.setText(Arad.preferences.getString(LocalMark.USER_NICKNAME.getName().toString(), ""));//更新显示下昵称
                    String imgUrl = Arad.preferences.getString("newPic");
                    if (imgUrl != null && !imgUrl.equals("")) {
                        Arad.imageLoader.load(imgUrl).into(new Target() {
                            @Override
                            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                                setBackground(bitmap);
                                headimgLogin.setImageBitmap(bitmap);
                            }

                            @Override
                            public void onBitmapFailed(Drawable errorDrawable) {
                                headimgLogin.setImageResource(R.mipmap.my_headimg);
                            }

                            @Override
                            public void onPrepareLoad(Drawable placeHolderDrawable) {
                                headimgLogin.setImageResource(R.mipmap.my_headimg);
                            }
                        });
                    }
                }
                break;
            case 22://进入设置 并点击设置中的退出登录时
                loadView();
                if (resultCode == Activity.RESULT_OK) {
                    message.setVisibility(View.GONE);//编辑信息隐藏
                }
//                else if(requestCode == 222){
//                    //实名认证
//                    loadView();
//                    String imgUrl = Arad.preferences.getString(LocalMark.USER_HEADIMG.getName().toString());
//                    if (imgUrl != null && !imgUrl.equals("")) {
//                        Arad.imageLoader.load(imgUrl).resize(361, 215).
//                                centerCrop().into(new Target() {
//                            @Override
//                            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//                                setBackground(bitmap);
//                                headimgLogin.setImageBitmap(bitmap);
//                            }
//
//                            @Override
//                            public void onBitmapFailed(Drawable errorDrawable) {
//                                headimgLogin.setImageResource(R.mipmap.my_headimg);
//                            }
//
//                            @Override
//                            public void onPrepareLoad(Drawable placeHolderDrawable) {
//                                headimgLogin.setImageResource(R.mipmap.my_headimg);
//                            }
//                        });
//                    }
//                }
                break;
            case 33:
                if (resultCode == Activity.RESULT_OK) {
                    loadView();
                }
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        dao.myMainView();//获取我的基本信息
    }
}
